import { defineStore } from 'pinia';
import { 
  Article, 
  ArticleListItem, 
  CreateArticleDTO, 
  UpdateArticleDTO 
} from '../types/article';
import { 
  getArticle, 
  getArticleList, 
  getPublishedArticles, 
  createArticle, 
  updateArticle, 
  deleteArticle 
} from '../api/article';

interface ArticleState {
  articles: ArticleListItem[];
  currentArticle: Article | null;
  loading: boolean;
  error: string | null;
  total: number;
  currentPage: number;
  pageSize: number;
}

export const useArticleStore = defineStore('article', {
  state: (): ArticleState => ({
    articles: [],
    currentArticle: null,
    loading: false,
    error: null,
    total: 0,
    currentPage: 1,
    pageSize: 10,
  }),
  
  getters: {
    getArticleById: (state) => {
      return (id: string) => state.articles.find(article => article.id === id);
    },
    isDraft: (state) => {
      return state.currentArticle?.status === 'draft';
    },
  },

  actions: {
    setLoading(loading: boolean): void {
      this.loading = loading;
    },

    setError(error: string | null): void {
      this.error = error;
    },

    async fetchArticles(page?: number, pageSize?: number, append: boolean = false): Promise<void> {
      try {
        this.setLoading(true);
        const params = {
          page: page || this.currentPage,
          page_size: pageSize || this.pageSize
        };
        const response = await getArticleList(params);
        const data = response.data;
        
        if (append && data.records.length > 0) {
          // 只有在有新数据时才追加
          this.articles = [...this.articles, ...data.records];
          this.currentPage = params.page;
        } else if (!append) {
          // 替换数据
          this.articles = data.records;
          this.currentPage = 1;
        }
        
        this.total = data.total;
        this.pageSize = params.page_size;
      } catch (error) {
        this.setError(error instanceof Error ? error.message : '获取文章列表失败');
      } finally {
        this.setLoading(false);
      }
    },

    async fetchPublishedArticles(page?: number, pageSize?: number, append: boolean = false): Promise<void> {
      try {
        this.setLoading(true);
        const params = {
          page: page || this.currentPage,
          page_size: pageSize || this.pageSize
        };
        const { data } = await getPublishedArticles(params);
        
        if (append) {
          // 追加新数据
          this.articles = [...this.articles, ...data.records];
        } else {
          // 替换数据
          this.articles = data.records;
        }
        
        this.total = data.total;
        this.currentPage = data.page;
        this.pageSize = data.pageSize;
      } catch (error) {
        this.setError(error instanceof Error ? error.message : '获取已发布文章列表失败');
      } finally {
        this.setLoading(false);
      }
    },

    async fetchArticleById(id: string): Promise<void> {
      try {
        this.setLoading(true);
        const { data } = await getArticle(id);
        this.currentArticle = data;
      } catch (error) {
        this.setError(error instanceof Error ? error.message : '获取文章详情失败');
        this.currentArticle = null;
      } finally {
        this.setLoading(false);
      }
    },

    async createArticle(articleData: CreateArticleDTO): Promise<string> {
      try {
        this.setLoading(true);
        const { data } = await createArticle(articleData);
        // 创建文章后重新获取第一页数据
        await this.fetchArticles(1);
        return data.id;
      } catch (error) {
        this.setError(error instanceof Error ? error.message : '创建文章失败');
        throw error;
      } finally {
        this.setLoading(false);
      }
    },

    async updateArticle(id: string, articleData: UpdateArticleDTO): Promise<void> {
      try {
        this.setLoading(true);
        const { data } = await updateArticle(id, articleData);
        if (this.currentArticle?.id === id) {
          this.currentArticle = data;
        }
        // 更新文章后重新获取第一页数据
        await this.fetchArticles(1);
      } catch (error) {
        this.setError(error instanceof Error ? error.message : '更新文章失败');
        throw error;
      } finally {
        this.setLoading(false);
      }
    },

    async deleteArticle(id: string): Promise<void> {
      try {
        this.setLoading(true);
        await deleteArticle(id);
        // 从列表中移除已删除的文章
        this.articles = this.articles.filter(article => article.id !== id);
        if (this.currentArticle?.id === id) {
          this.currentArticle = null;
        }
      } catch (error) {
        this.setError(error instanceof Error ? error.message : '删除文章失败');
        throw error;
      } finally {
        this.setLoading(false);
      }
    },
  },
});